from django.db import transaction
from rest_framework.response import Response

from orders.models import OrderInfo
from rest_framework import serializers
from goods.models import *


class SKUSpecificationSerializer(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()

    class Meta:
        model = SKUSpecification
        fields = ('spec_id', 'option_id')


class SKUSerializer(serializers.ModelSerializer):
    # 指定分类信息
    category = serializers.StringRelatedField()
    # 指定分类信息
    category_id = serializers.IntegerField()
    # 关联嵌套返回
    spu = serializers.StringRelatedField()
    # 指定关联的spu表的信息
    spu_id = serializers.IntegerField()

    # 指定关联的选项信息，关联嵌套返回
    specs = SKUSpecificationSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    # 重写创建
    def create(self, validated_data):
        specs = validated_data.pop('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                sku = SKU.objects.create(**validated_data)

                for spec in specs:
                    spec['sku_id'] = sku.id
                    SKUSpecification.objects.create(**spec)
            except Exception as e:
                transaction.rollback(save_point)
            transaction.savepoint_commit(save_point)

        return sku

    # 重写更新（修改数据）
    def update(self, instance, validated_data):
        specs = validated_data.pop('specs')
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                # 更新主表SKU数据
                # super().update(instance,validated_data)
                SKU.objects.filter(pk=instance.id).update(**validated_data)
                # 先删除原有中间表数据，然后再插入新的数据
                SKUSpecification.objects.filter(sku_id=instance.id).delete()
                for spec in specs:
                    spec['sku_id'] = instance.id
                    SKUSpecification.objects.create(**spec)
            except Exception as e:
                transaction.rollback(save_point)
            transaction.savepoint_commit(save_point)
        return SKU.objects.get(pk=instance.id)


class SKUCategoriesSerializer(serializers.ModelSerializer):
    """
    商品分类序列化器
    """

    class Meta:
        model = GoodsCategory
        fields = '__all__'


class SpecificationOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields = '__all__'


class SPUSpecSerializer(serializers.ModelSerializer):
    """
    商品SPU表序列化器
    """
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()
    options = SpecificationOptionSerializer(many=True)

    class Meta:
        model = SPUSpecification
        fields = '__all__'


# SPU表管理序列化
class SPUSerializer(serializers.ModelSerializer):
    brand = serializers.StringRelatedField()
    brand_id = serializers.IntegerField()

    category1_id = serializers.IntegerField()
    category2_id = serializers.IntegerField()
    category3_id = serializers.IntegerField()

    class Meta:
        model = SPU
        exclude = ('category1', 'category2', 'category3',)


# 品牌信息
class BrandSerializer(serializers.ModelSerializer):
    class Meta:
        model = Brand
        fields = '__all__'


# 一级分类
class GoodsChannelSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'


# 规格表序列化
class SpecifcationSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField()
    spu_id = serializers.IntegerField()

    class Meta:
        model = SPUSpecification
        fields = '__all__'


# 规格选项表序列化
class OptionsSerializer(serializers.ModelSerializer):
    spec = serializers.StringRelatedField()
    spec_id = serializers.IntegerField()

    class Meta:
        model = SpecificationOption
        fields = '__all__'


class SPUOptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPUSpecification
        fields = '__all__'


# 图片表序列化
from fdfs_client.client import Fdfs_client
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile


class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = '__all__'

    def validate(self, attrs):
        image = attrs.get('image')
        print(image, type(image))
        if not image or not isinstance(image, InMemoryUploadedFile):
            return serializers.ValidationError('这文件不符合')
        return attrs

    def create(self, validated_data):
        client = Fdfs_client(settings.FASTDFS_PATH)
        ret = client.upload_by_buffer(validated_data.get('image').read())
        validated_data['image'] = ret.get('Remote file_id').replace('\\', '/')
        return SKUImage.objects.create(**validated_data)

    def update(self, instance, validated_data):
        client = Fdfs_client(settings.FASTDFS_PATH)
        ret = client.upload_by_buffer(validated_data.get('image').read())
        validated_data['image'] = ret.get('Remote file_id').replace('\\', '/')
        return super(ImageSerializer, self).update(instance, validated_data)


class SKUImageSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')
